<template>
  <div class="app-container">
    <div>
      <!-- 条件栏 -->
      <NewPageFilter
        v-model:query="filterInfo.query.queryParams"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :slipSelectRequest="slipSelectRequest"
      >
        <template v-slot:filter-time>
          <el-date-picker
            @change="timeChange"
            v-model="time"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            align="right"
            :shortcuts="$fn.pickerDateOptionsNoCurDateFn().shortcuts"
            :disabled-date="datePickerOptions.disabledDate"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </template>
        <template v-slot:filter-productId>
          <el-input
            class="not-mongolia"
            type="input"
            :disabled="true"
            placeholder="请选择产品"
            v-model="productNameList"
          >
            <template #append>
              <el-icon @click="openProductWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </NewPageFilter>

      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"></NewPageFilter>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :checkBox="false"
        :listen-height="true"
        rowKey="_index"
        :handle="tableInfo.handle"
        :tab-index="true"
        :summary="true"
        :summaryFieldList="tableInfo.summaryFieldList"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        @pageInfo="pageInfo"
        @exChange="exChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-storeAmount="scope">
          <span
            v-if="$permission('warehouseAffair:list')"
            class="slip-edit"
            @click="showDetail(scope.row, '1')"
            >{{ $fn.TripartiteMethod(scope.row.storeAmount || 0) }}</span
          >
          <span v-else>{{
            $fn.TripartiteMethod(scope.row.storeAmount || 0)
          }}</span>
        </template>
        <template v-slot:col-exportAmount="scope">
          <span
            v-if="$permission('warehouseAffair:list')"
            class="slip-edit"
            @click="showDetail(scope.row, '0')"
            >{{ $fn.TripartiteMethod(scope.row.exportAmount || 0) }}</span
          >
          <span v-else>{{
            $fn.TripartiteMethod(scope.row.exportAmount || 0)
          }}</span>
        </template>
        <template v-slot:col-expand>
          <el-row :gutter="20" style="width: 100%">
            <el-col :span="12" class="expandCol">
              <PageTable
                class="expandTable"
                v-model:data="expandTableInfo.storeData"
                :checkBox="false"
                :listen-height="true"
                rowKey="_index"
                :tab-index="true"
                :field-list="expandTableInfo.fieldList"
                :pager="false"
                style="background: #fceacb"
              />
            </el-col>
            <el-col :span="12" class="expandCol">
              <PageTable
                class="expandTable"
                v-model:data="expandTableInfo.exportData"
                :checkBox="false"
                :listen-height="true"
                rowKey="_index"
                :tab-index="true"
                :field-list="expandTableInfo.fieldList"
                :pager="false"
                style="background: #fceacb"
              />
            </el-col>
          </el-row>
        </template>
      </TableContainer>
    </div>
    <NewSelectProduct
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      v-model:query="productInfo.query.queryMap"
      :api="productInfo.api"
      :saveEmpty="true"
      :query-params="productInfo.query.queryParams"
      tableKey="PurchaseSaleStorageGroupByProductQuery-com.slip.spd.entity.vo.core.CoreProductVONew"
      :show-price="productInfo.priceShow"
      @callback="selectProduct"
    />
    <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
  </div>
</template>

<script setup name="productDetailsSummary">
import { getDepotAll, getDeptAll, getSupplierAll } from '@/api/core'
import {
  purchaseSaleStorageQueryPage,
  purchaseSaleStorageQueryPrint,
  purchaseSaleStorageQueryExcel,
  purchaseSaleCoreProductQuery,
} from '@/api/dataQuery'

import moment from 'moment'

import { getCustomizeSetting } from '@/api/customize'
import utils from '@/common/js/utils'
import { depotAffairTypeSummaryAll } from '@/api/stock'
import _ from 'lodash'
import { fatchTemplateByCode } from '@/api/base'
const { proxy } = getCurrentInstance()
const productList = ref([])
const time = ref(null)
const productNameList = ref('')
const datePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > +new Date() - 3600 * 1000 * 24
  },
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryParams: {
      startDate: '',
      endDate: '',
      depotIdMult: '',
      deptIdMult: '',
      productId: '',
      isConsignBusiness: '',
    },
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
    groupMap: {},
    groups: [],
  },
  searchList: [
    { label: '时间', value: 'time', slot: true },

    {
      label: '产品',
      slot: true,
      value: 'productId',
    },
    {
      componentType: 'slip-select',
      label: '仓库',
      value: 'depotIdMult',
      api: getDepotAll,
      query: {
        status: '1',
        depotAuth: 'id',
        searchType: 'depot',
        useTypeId: '1',
      },
      multiple: true,
      event: search,
    },
    {
      componentType: 'slip-select',
      label: '部门',
      value: 'deptIdMult',
      api: getDeptAll,
      query: {
        status: '1',
        deptAuth: 'id',
        searchType: 'dept',
      },
      multiple: true,
      event: search,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      asValue: 'isConsignBusiness',
      componentType: 'select-model',
      code: 'yes_or_no',
      event: search,
    },
    {
      label: '是否暂估入库',
      value: 'isEstimationStockBusinessValue',
      asValue: 'isEstimationStockBusiness',
      componentType: 'select-model',
      code: 'yes_or_no',
      event: search,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: { sort: 'create_time desc' },
      clearable: true,
      multiple: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      event: search,
    },
    {
      label: '入库批次号',
      value: 'storeBatchNumber',
      componentType: 'input',
      event: search,
    },
    {
      label: '库存类别',
      value: 'inventoryCategoriesValue',
      asValue: 'inventoryCategories',
      componentType: 'select-model',
      code: 'inventory_categories',
      event: search,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      type: 'button',
      label: '打印',
      event: print,
      show: proxy.$permission('productDetailsSummary:print'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: true,
    },
  ],
})
const expandTableInfo = ref({
  storeData: [],
  exportData: [],
  fieldList: [
    { label: '出入库类型', value: 'exportStoreTypeValue' },
    {
      label: '数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    { label: '操作类型', value: 'typeValue' },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  summaryFieldList: [
    { value: 'beginQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'beginAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'storeQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'storeAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'exportQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'exportAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'endQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'endAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'netQty', formatter: proxy.$fn.TripartiteMethod },
    { value: 'netAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'pendStoreQty', formatter: proxy.$fn.TripartiteMethod },
    { value: 'pendStoreAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  selections: [],
  fieldList: [],
})
//选择产品相关
const productInfo = ref({
  api: purchaseSaleCoreProductQuery,
  priceShow: true,
  visible: false,
  query: {
    queryMap: {},
    queryParams: {},
  },
})
const slipSelectRequest = ref(true)

function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
const excelPrint = ref({
  type: 'print', // 类型print/excel
  print: {
    fatchTemplateByCode: {
      // 获取打印模板参数
      resourceCode: 'productDetailsSummary:print',
      isDefault: 1,
    },
    api: purchaseSaleStorageQueryPrint, // 打印数据接口
    params: {}, // 打印参数
  },
  excel: {
    api: purchaseSaleStorageQueryExcel, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//打印
function print() {
  excelPrint.value.type = 'print'
  excelPrint.value.print.params = proxy.$fn.deepClone({
    customizeDto: filterInfo.value.query,
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
/* function exportExcel() {
  purchaseSaleStorageQueryExcel(
    proxy.$fn.delEmptyAttribute(filterInfo.value.query)
  ).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function print() {
  fatchTemplateByCode({
    resourceCode: 'productDetailsSummary:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      let params = {
        customizeDto: filterInfo.value.query,
      }
      purchaseSaleStorageQueryPrint(params).then((resp) => {
        if (resp && resp.success) {
          let data = proxy.$fn.deepClone(resp.data)
          let newData = data.map((item) => {
            return {
              ...item,
              ...item.orderInfo,
            }
          })
          proxy.$lodop.preview(temp, newData)
        }
      })
    }
  })
} */
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryParams.startDate = val[0]
    filterInfo.value.query.queryParams.endDate = val[1]
  } else {
    filterInfo.value.query.queryParams.startDate = ''
    filterInfo.value.query.queryParams.endDate = ''
  }
}
function showDetail(row, type) {
  let operateTime = null
  if (filterInfo.value.query.queryParams.startDate) {
    operateTime =
      filterInfo.value.query.queryParams.startDate +
      ' 00:00:00' +
      ',' +
      filterInfo.value.query.queryParams.endDate +
      ' 23:59:59'
  }
  proxy.$router.push({
    name: 'warehouseAffair',
    params: {
      query: JSON.stringify({
        queryMap: {
          deptId: {
            queryType: 'IN',
            value: row.deptId,
          },
          depotId: {
            queryType: 'IN',
            value: row.depotId,
          },
          price: {
            queryType: 'IN',
            value: row.price,
          },
          operateTime: {
            queryType: 'BETWEEN',
            value: operateTime,
          },
          // productId: {
          //   queryType: "IN",
          //   value: row.productId
          // },
          productCode: {
            queryType: 'IN',
            value: row.productCode,
          },
          exportStoreType: {
            queryType: 'IN',
            value: type,
          },
          isConsignBusiness: {
            queryType: 'IN',
            value: filterInfo.value.query.queryParams.isConsignBusiness,
          },
          supplierId: {
            queryType: 'IN',
            value: filterInfo.value.query.queryParams.supplierIdMult,
          },
        },
      }),
    },
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.value.data = data.map((item, index) => {
        return {
          ...item,
          _index: index + 1,
        }
      })
      break
  }
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    productList.value = rows
    filterInfo.value.query.queryParams.productIdMult = rows
      .map((item) => item.id)
      .toString()
    productNameList.value = rows.map((item) => item.commonName).toString()
  } else {
    productList.value = []
    filterInfo.value.query.queryParams.productIdMult = ''
    productNameList.value = ''
  }
}
function openProductWindow() {
  const { depotIdMult, deptIdMult, startDate, endDate } =
    filterInfo.value.query.queryParams

  if (!startDate || !endDate) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择查询时间！',
    })
    return
  }
  productInfo.value.query.queryParams.depotIdMult = depotIdMult
  productInfo.value.query.queryParams.deptIdMult = deptIdMult
  productInfo.value.query.queryParams.startDate = startDate
  productInfo.value.query.queryParams.endDate = endDate
  productInfo.value.visible = true
}
function exChange(data, expandedRows) {
  if (expandedRows.length > 0) {
    let params = {
      depotId: data.depotId,
      price: data.price,
      productId: data.productId,
      startDate: filterInfo.value.query.queryParams.startDate,
      endDate: filterInfo.value.query.queryParams.endDate,
      isConsignBusiness: filterInfo.value.query.queryParams.isConsignBusiness,
    }
    depotAffairTypeSummaryAll(params).then((resp) => {
      if (resp && resp.success) {
        let newData = resp.data.map((item, index) => {
          return {
            ...item,
            _index: index,
          }
        })
        let data = _.groupBy(newData, 'exportStoreType')
        expandTableInfo.value.exportData = data[0]
        expandTableInfo.value.storeData = data[1]
      }
    })
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'PurchaseSaleStorageGroupByProductQueryList-com.slip.spd.entity.vo.dataquery.PurchaseSaleStorageGroupByProductQueryVO',
  }
  getCustomizeSetting(param).then((res) => {
    let data = res.data
    filterInfo.value.query.customizeUserVO = data
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList.forEach((item) => {
        item.show = true
      })
      tableInfo.value.api = purchaseSaleStorageQueryPage
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
    }
  })
}

let obj = {
  expand: {
    label: '',
    value: 'expand',
    columnType: 'expand',
    type: 'slot',
    show: false,
    hidden: true,
  },
  beginQty: {
    label: '期初总量',
    value: 'beginQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  storeQty: {
    label: '入库总量',
    value: 'storeQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  exportQty: {
    label: '出库总量',
    value: 'exportQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  endQty: {
    label: '期末总量',
    value: 'endQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  pendStoreQty: {
    label: '待入库数量',
    value: 'pendStoreQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  netQty: {
    label: '净总量',
    value: 'netQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  beginAmount: {
    label: '期初总金额',
    value: 'beginAmount',
    type: 'column',
    componentType: 'price',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  storeAmount: {
    label: '入库总金额',
    value: 'storeAmount',
    type: 'slot',
    componentType: 'price',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  exportAmount: {
    label: '出库总金额',
    value: 'exportAmount',
    type: 'slot',
    componentType: 'price',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  endAmount: {
    label: '期末总金额',
    value: 'endAmount',
    type: 'column',
    componentType: 'price',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  pendStoreAmount: {
    label: '待入库总金额',
    value: 'pendStoreAmount',
    type: 'column',
    componentType: 'price',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  netAmount: {
    label: '净总金额',
    value: 'netAmount',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  startDate: {
    label: '查询开始日期',
    value: 'startDate',
    componentType: 'dateTime',
    show: false,
    hidden: true,
  },
  endDate: {
    label: '查询截止日期',
    value: 'endDate',
    componentType: 'dateTime',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

onMounted(() => {
  proxy.$nextTick(() => {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    end.setTime(end - 3600 * 1000 * 24)
    filterInfo.value.query.queryParams.startDate =
      moment(start).format('YYYY-MM-DD')
    filterInfo.value.query.queryParams.endDate =
      moment(end).format('YYYY-MM-DD')
    time.value = [
      moment(start).format('YYYY-MM-DD'),
      moment(end).format('YYYY-MM-DD'),
    ]
  })
})
</script>

<style scoped lang="scss">
:deep(.el-table) .el-table__expanded-cell[class*='cell'] {
  background: #fceacb !important;
}
:deep(.expandTable) .el-table tr,
:deep(.expandTable) .el-table td,
:deep(.expandTable) .el-table th {
  background: #fceacb !important;
}
:deep(.el-tag) {
  margin: 2px 5px 2px 0;
}
</style>
